<template>
    <div>
        <div style="display: flex;flex-direction: column;height: 100vh">
            <mt-header :title="'订单 - '+mvvm.headerText" style="flex: 0 0 7%">
                <mt-button slot="left" icon="back" @click="back">返回</mt-button>
                <mt-button slot="right" @click.native="showOrder(-1)" style="font-size: 30px;margin-right: 10px">＋
                </mt-button>
                <mt-button icon="more" slot="right" style="font-size: 20px"
                           @click.native="mvvm.sheetVisible=true"></mt-button>

            </mt-header>

            <!--搜索-->
            <mt-search
                    v-model="searchText"
                    cancel-text="取消"
                    placeholder="旺旺号"
                    style="height: auto"
                    autocomplete="off"
            >
            </mt-search>
            <!--订单列表-->
            <mt-loadmore :top-method="loadTop" style="flex:1;overflow-y: auto" ref="loadmore">
                <div class="order-item" v-for="(item,index) in orders" :key="index" :style="{backgroundColor:item.status==1?'white':'orange'}">
                    <div @click="showOrder(-2,item)">
                        <div style="display: inline-block;width:100%;">
                            <div style="float:left;color: orange;font-size: 15px">{{index+1}})&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            </div>

                            <div style="float:left;color: blue;font-size: 15px">{{item.account}}</div>
                            <div style="float:right;color: red;font-size: 15px">{{item.orderDate.substring(0,16)}}</div>
                        </div>
                        <div style="display: inline-block;width:100%;">
                            <div style="color: red">产&nbsp;&nbsp;品：{{item.product}}</div>
                        </div>
                        <div style="display: inline-block;width:100%;">
                            <div style="width: 50%;color: red;float: left;">应付价：<span
                                    style="color: black">{{item.payablePrice}}</span>
                            </div>
                            <div style="width: 50%;color: red;float: left;">实付价：<span
                                    style="color: black">{{item.paidPrice}}</span>
                            </div>
                        </div>
                        <div style="display: inline-block;width:100%;">
                            地&nbsp;&nbsp;址：{{item.address}}
                        </div>
                    </div>

                    <div style="display: inline-block;width:80%">
                        备&nbsp;&nbsp;住：{{item.remark}}
                    </div>
                    <div style="padding:0 5px;float: right;font-size:25px;margin: auto auto"
                         @click="deleteOrder(item.id)">
                        ×
                    </div>
                </div>
            </mt-loadmore>
        </div>


        <!--添加/修改订单信息模态框-->
        <mt-popup
                style="width: 100%;height: 100%"
                v-model="mvvm.formDataVisible"
                position="right"
                :modal="false"
                class="vue-parent"
        >
            <div style="width: 100%;height: 100%">
                <mt-header title="美美护肤 - 订单" style="height: 7%">
                    <mt-button slot="left" icon="back" @click.native="mvvm.formDataVisible=false">返回</mt-button>
                    <mt-button slot="right" @click.native="saveOrder">{{orderStatusText}}</mt-button>
                </mt-header>
                <div style="width: 100%;height: 93%;overflow-y: auto">
                    <form id="addOrderForm">
                        <mt-field style="display: none" v-model="mvvm.orderObj.id"></mt-field>
                        <mt-field label="旺旺号" placeholder="请输入旺旺号" :readonly="mvvm.readonly.account" type="text"
                                  :attr="{ name:'account'}"
                                  v-model.trim="mvvm.orderObj.account"></mt-field>
                        <mt-field label="下单时间" placeholder="时间格式xxxx-xx-xx xx:xx" type="datetime"
                                  :attr="{ name:'orderDate'}"
                                  v-model="mvvm.orderObj.orderDate"></mt-field>
                        <mt-field label="订单号" placeholder="请输入订单号" :attr="{ name:'orderNumber'}"
                                  v-model="mvvm.orderObj.orderNumber"></mt-field>
                        <mt-field label="产品" @click.native="mvvm.productVisible=true" placeholder="请输入产品"
                                  :readonly="true"
                                  type="text" :attr="{ name:'product'}" v-model="mvvm.orderObj.product"></mt-field>
                        <mt-field label="应付价" placeholder="请输入应付价" type="number" :attr="{ name:'payablePrice'}"
                                  v-model="mvvm.orderObj.payablePrice"></mt-field>
                        <mt-field label="实付价" placeholder="请输入实付价" type="number" :attr="{ name:'paidPrice'}"
                                  v-model="mvvm.orderObj.paidPrice"></mt-field>
                        <mt-field label="礼品价" placeholder="请输入礼品价" type="number" :attr="{ name:'giftPrice'}"
                                  v-model="mvvm.orderObj.giftPrice"></mt-field>
                        <mt-field label="联系方式" placeholder="请输入联系方式" type="text" :attr="{ name:'phone'}"
                                  v-model="mvvm.orderObj.phone"></mt-field>
                        <mt-field label="来源" placeholder="请输入来源" :readonly="true" type="text"
                                  :attr="{ name:'sourceText'}"
                                  v-model="mvvm.orderObj.sourceText"
                                  @click.native="mvvm.sourceVisible=true"></mt-field>
                        <mt-field label="收货地址" placeholder="请输入收货地址" type="text" :attr="{ name:'address'}"
                                  v-model="mvvm.orderObj.address"></mt-field>
                        <mt-field label="备注" placeholder="备注" type="textarea" rows="3" :attr="{ name:'remark'}"
                                  v-model="mvvm.orderObj.remark"></mt-field>
                    </form>
                </div>

            </div>
        </mt-popup>
        <!--产品选择-->
        <mt-popup
                v-model="mvvm.productVisible"
                position="bottom"
                style=" width:100%"
        >
            <mt-picker :slots="slots" :show-toolbar="true" visible-Item-Count="5" valueKey="name"
                       @change="onPickerChange">
                <div style="display: inline-block;width: 100%">
                    <div style="margin: 10px;font-size: 18px;color: #8D8D8D;float: left" @click="onClearProduct">清空
                    </div>
                    <div style="margin: 10px;text-align: right;font-size: 20px;color: #0000FF;float: right"
                         @click="onSelectEnter">确定
                    </div>
                </div>
            </mt-picker>
        </mt-popup>
        <!--header更多-->
        <mt-actionsheet
                :actions="actions"
                cancel-Text=''
                v-model="mvvm.sheetVisible">
        </mt-actionsheet>
        <!--来源选择-->
        <mt-popup
                v-model="mvvm.sourceVisible"
                position="bottom"
                style=" width:100%"
        >
            <mt-picker :slots="sourceSlots" :show-toolbar="true" visible-Item-Count="5" valueKey="key"
                       @change="onSourcePickerChange">
                <div style="margin: 10px;text-align: right;font-size: 20px;color: #0000FF" @click="onSourceSelectEnter">
                    确定
                </div>
            </mt-picker>
        </mt-popup>
    </div>

</template>

<script>
    import {Toast, MessageBox} from 'mint-ui';

    export default {
        name: "order",
        data() {
            return {
                status: {
                    orderAdd: true
                },
                // 所有产品
                products: [
                    {
                        id: 1,
                        productName: "美白三件套",
                        weight: 2,
                        type: 1
                    }
                ],
                // 所有订单
                orders: [

                    //orderBean
                ],
                // 订单实体模型
                orderBean: {
                    id: -1,
                    account: "",
                    orderDate: "",
                    orderNumber: "",
                    product: "",
                    payablePrice: "",
                    paidPrice: "",
                    giftPrice: 0,
                    productDetailjson: "",
                    sourceText: this.$Dictionary.source[0].key,
                    source: this.$Dictionary.source[0].value,
                    address: "",
                    phone: "",
                    remark: ""
                },
                // 选中产品
                selectProducts: [
                    // {
                    //     Name:"",
                    //     ProductId:"",
                    //     Count:""
                    // }
                ],
                slots: [
                    {
                        flex: 2,
                        values: [
                            {
                                type: 1,
                                name: "统一系列"
                            }
                        ],
                        className: 'slot1',
                        textAlign: 'right'
                    }, {
                        flex: 0.5,
                        divider: true,
                        content: '-',
                        className: 'slot2'
                    },
                    {
                        flex: 3,
                        values: [
                            // {
                            //     id: 1,
                            //     name: "美白三件套"
                            // }
                        ],
                        className: 'slot3',
                        textAlign: 'left'
                    }, {
                        flex: 0.5,
                        divider: true,
                        content: '-',
                        className: 'slot4'
                    }, {
                        flex: 1,
                        values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 18, 20, 25, 30],
                        className: 'slot5',
                        textAlign: "right",
                    }
                ]
                ,
                sourceSlots: [
                    {
                        flex: 1,
                        values: this.$Dictionary.source,
                        className: 'slot1',
                    }
                ],
                actions: [
                    {
                        name: "当月订单", method: function () {
                            this.getAllOrders(-1)
                        }.bind(this)
                    },
                    {
                        name: "最近30天订单", method: function () {
                            this.getAllOrders(-2)
                        }.bind(this)
                    },
                    {
                        name: "最近60天订单", method: function () {
                            this.getAllOrders(-3)
                        }.bind(this)
                    },
                    {
                        name: "最近90天订单", method: function () {
                            this.getAllOrders(-4)
                        }.bind(this)
                    }
                ],
                // 搜索内容
                searchText: "",
                mvvm: {
                    sourceVisible: false,
                    productVisible: false,
                    sheetVisible: false,
                    // 订单表单模型与订单实体模型一样
                    formDataVisible: false,
                    orderObj: {
                        id: -1,
                        account: "",
                        orderDate: "",
                        orderNumber: "",
                        product: "",
                        payablePrice: "",
                        paidPrice: "",
                        giftPrice: 0,
                        productDetailjson: "",
                        sourceText: "",
                        source: "",
                        address: "",
                        phone: "",
                        remark: ""
                    },
                    readonly: {
                        account: false
                    },
                    headerText: "最近30天"
                },
                // 搜索计算时间间隔
                timeId: {},
                orderStatusText: "添加",
                // 产品picker
                oldProductPicker: [],
                oldSourcePicker: [],
                // 最近订单类型
                orderCode: -2
            }
        },
        computed: {
            address() {
                return this.mvvm.orderObj.address
            },
            phone() {
                return this.mvvm.orderObj.phone
            },
            payablePrice() {
                return this.mvvm.orderObj.payablePrice
            }

        },
        watch: {
            payablePrice(value) {
                if (this.status.orderAdd) {
                    this.mvvm.orderObj.paidPrice = value;
                }
            },
            address(value) {
                var addrArr = value.split("：");
                var arr;
                if (addrArr.length == 2) {
                    arr = addrArr[1].split("，");
                } else {
                    arr = addrArr[0].split("，");
                }
                this.decompose(arr);
            },
            phone(value) {
                var addrArr = value.split("：");
                var arr;
                if (addrArr.length == 2) {
                    arr = addrArr[1].split("，");
                } else {
                    arr = addrArr[0].split("，");
                }
                this.decompose(arr);

            },
            // 搜索文本
            searchText(value) {
                var _this = this;
                clearTimeout(this.timeId);
                if (value.length <= 1) {
                    return;
                }

                this.timeId = setTimeout(function () {
                    $('.mint-search-list').css('display', 'none');
                    _this.searchOrder();
                }, 500);

            },
            selectProducts(value) {
                if (value.length == 0) {
                    return;
                }
                if (!this.mvvm.orderObj.product) {
                    value.splice(0, value.length, value[value.length - 1]);
                }
                var str = "";
                for (let item of value) {
                    if (item.Count === 1) {
                        str = str + item.Name.concat("+");
                    } else {
                        str = str + item.Name.concat("*", item.Count, "+");
                    }
                }
                str = str.substring(0, str.length - 1);
                this.mvvm.orderObj.product = str;
                this.mvvm.orderObj.productDetailjson = JSON.stringify(value);
            },
            products(value) {
                var _this = this;
                this.slots[2].values = [];
                for (let i = 0; i < value.length; i++) {
                    if (value[i].category == this.slots[0].values[0].code) {
                        this.slots[2].values.push({id: value[i].id, name: value[i].productName});
                    }
                }
            }
        },
        methods: {
            // 解析地址字符串
            decompose(arr) {
                if (arr.length === 4) {
                    this.mvvm.orderObj.phone = arr[0] + "，" + arr[1];
                    this.mvvm.orderObj.address = arr[2] + "，" + arr[3];
                } else if (arr.length > 4) {
                    var reg = /^[0-9]$/;
                    if (reg.test(arr[2].substr(0, 1))) {
                        this.mvvm.orderObj.phone = arr[0] + "，" + arr[1] + "，" + arr[2];
                        this.mvvm.orderObj.address = arr[3] + "，" + arr[4];
                    } else {
                        this.mvvm.orderObj.phone = arr[0] + "，" + arr[1];
                        this.mvvm.orderObj.address = arr[2] + "，" + arr[3] + "，" + arr[4];
                    }
                }
            },
            // 下拉刷新
            loadTop: function () {
                // 获取所有订单
                var _this = this;
                this.getAllOrders(this.orderCode, function () {
                    _this.$refs.loadmore.onTopLoaded();
                });

            },
            // 产品选择确定按钮
            onSelectEnter: function () {
                var _this = this;
                try {
                    this.selectProducts.map(o => {
                        if (o.ProductId === _this.oldProductPicker[1].id) {
                            _this.layer.msg("已选择该产品", {time: 1000});
                            throw "error"
                        }
                    });
                } catch (e) {
                    return
                }
                this.selectProducts.push({
                    Name: this.oldProductPicker[1].name,
                    ProductId: this.oldProductPicker[1].id,
                    Count: parseInt(this.oldProductPicker[2])
                });
                this.mvvm.productVisible = false;
            },
            // 产品清空
            onClearProduct: function () {
                this.selectProducts = [];
                this.$set(this.mvvm.orderObj, 'product', "");
                this.mvvm.productVisible = false;
            },
            // 来源选择确定按钮
            onSourceSelectEnter: function () {
                this.mvvm.orderObj.sourceText = this.oldSourcePicker[0].key;
                this.mvvm.orderObj.source = this.oldSourcePicker[0].value;
                this.mvvm.sourceVisible = false;
            },
            // 来源选择change事件
            onSourcePickerChange: function (picker, values) {

                this.oldSourcePicker = window.copy(values);
            },
            //产品选择change
            onPickerChange: function (picker, values) {
                if (!!this.oldProductPicker[0]) {

                    if (this.oldProductPicker[0].code != values[0].code) {

                        this.slots[2].values = [];
                        for (let i = 0; i < this.products.length; i++) {
                            if (this.products[i].category == values[0].code) {
                                this.slots[2].values.push({
                                    id: this.products[i].id,
                                    name: this.products[i].productName
                                });
                            }
                        }
                    }
                }
                this.oldProductPicker = window.copy(values);

            },
            searchOrder: function () {
                var _this = this;
                this.$http.get(this.$Api.order.searchOrder.concat("?account=", this.searchText)).then((res) => {
                    var resp = res.data;
                    if (resp.code === _this.$ResponseCode.ok) {
                        _this.orders = resp.info.data;
                        window.successNotify(Toast, resp.info.msg);
                    } else {
                        window.failedNotify(Toast, resp.info.msg);
                    }
                });
            },
            /**
             * 保存订单
             * @param code -1为添加，非-1为订单实体对象
             * @param item 订单对象
             */
            showOrder: function (code = -1, item) {
                this.mvvm.orderObj.id = "";
                if (code === -1) {
                    this.status.orderAdd = true;
                    this.mvvm.orderObj.id = -1;
                    this.orderStatusText = "添加";
                    this.mvvm.orderObj = window.copy(this.orderBean);
                    this.selectProducts = [];
                    this.mvvm.readonly.account = false;
                } else if (code == -2) {
                    this.status.orderAdd = false;
                    this.orderStatusText = "修改";
                    // 订单拷贝
                    this.mvvm.orderObj = window.copy2(item);
                    // 修改状态下旺旺名不可修改
                    this.mvvm.readonly.account = true;
                    // 匹配来源code相关key
                    this.mvvm.orderObj.sourceText = this.$Dictionary.source.map(o => {
                        if (o.value == parseInt(this.mvvm.orderObj.source)) {
                            return o.key;
                        }
                    })[0];
                    // 产品从文本转已选择产品对象，文本与selectProducts对象关联
                    if (!!this.mvvm.orderObj.productDetailjson) {
                        this.selectProducts = JSON.parse(this.mvvm.orderObj.productDetailjson);
                    } else {
                        this.selectProducts = [];
                    }
                }
                this.mvvm.formDataVisible = true;
            },
            // code -1为添加-2为修改
            saveOrder: function () {

                var _this = this;
                $('#addOrderForm').validate({
                    rules: {
                        account: {
                            required: true,
                            minlength: 2,
                        },
                        orderDate: {
                            required: true,
                            date: true,
                            cstdate: true
                        },
                        orderNumber: {
                            required: true,
                            minlength: 10,
                            maxlength: 32
                        },
                        product: {
                            required: true,
                            products: true
                        },
                        payablePrice: {
                            required: true,
                            min: 1,
                            max: 10000
                        },
                        paidPrice: {
                            required: true,
                            min: 1,
                            max: 10000
                        },
                        giftPrice: {
                            required: true,
                            max: 50
                        },
                        phone: {
                            required: true,
                            minlength: 11,
                            maxlength: 20
                        },
                        sourceText: {
                            required: true,
                        },
                        address: {
                            required: true,
                            minlength: 6,
                        },
                    }
                });
                if (!!$('#addOrderForm').valid()) {
                    var url = this.$Api.order.order;
                    if (this.status.orderAdd) {

                    } else {
                        url = url.concat("?_method=put")
                    }
                    this.$http.post(url, this.mvvm.orderObj).then(function ({data: resp} = res) {
                        if (resp.code === _this.$ResponseCode.ok) {
                            window.successNotify(Toast, resp.info.msg);
                            _this.mvvm.formDataVisible = false;
                            _this.getAllOrders(-2);
                        } else {
                            window.failedNotify(Toast, resp.info.msg);
                        }
                    }.bind(this));

                } else {

                }


            },
            deleteOrder: function (id) {
                var _this = this;
                MessageBox.confirm('确定删除该项妈?').then(action => {
                    //按钮【按钮一】的回调
                    _this.$http.delete(this.$Api.order.order,{
                        params:{
                            id:id
                        },
                        headers:{
                           'Content-Type': 'application/x-www-form-urlencoded'
                        }
                    }).then(function ({data: resp} = res) {
                        if (resp.code === _this.$ResponseCode.ok) {
                            _this.getAllOrders(-2);
                            window.successNotify(Toast, resp.info.msg)
                        } else {
                            window.failedNotify(Toast, resp.info.msg);
                        }
                    }.bind(_this));
                });


            },
            // 获取所有产品系列类别
            getAllProductCategory: function () {
                var _this = this;
                this.$http.get(this.$Api.basic.productCategory.concat("?code=", 2)).then((res) => {
                    var resp = res.data;
                    if (resp.code == _this.$ResponseCode.ok) {
                        // 获取所有产品信息
                        _this.slots[0].values = resp.info.data.map(function (item) {
                            return {code: item.code, name: item.value}
                        });
                        _this.getAllProducts();
                    } else {
                        window.failedNotify(Toast, resp.info.msg);
                    }
                });

            },
            /**
             * 获取所有产品
             */
            getAllProducts: function () {
                var _this = this;
                this.$http.get(this.$Api.basic.allProducts).then((res) => {
                    var resp = res.data;
                    if (resp.code === _this.$ResponseCode.ok) {
                        _this.products = resp.info.data;
                    } else {
                        window.failedNotify(Toast, resp.info.msg);
                    }
                });
            },
            /**
             *
             * @param code -1为本月，-2为30天前，-3 为60天前，-4 为90天其余为30天前
             * @param onCallback 回调函数
             */
            getAllOrders: function (code = -2, onCallback) {
                var _this = this;
                this.$http.get(this.$Api.order.orders.concat("?code=", code)).then((res) => {
                    var resp = res.data;
                    if (resp.code === _this.$ResponseCode.ok) {
                        _this.orders = resp.info.data;

                        if (!!onCallback) {
                            onCallback()
                        }
                        _this.mvvm.sheetVisible = false;
                        _this.orderCode = code;
                        switch (code) {
                            case -1:
                                _this.mvvm.headerText = "当月订单"
                                break;
                            case -2:
                                _this.mvvm.headerText = "最近30天"
                                break;
                            case -3:
                                _this.mvvm.headerText = "最近60天"
                                break;
                            case -4:
                                _this.mvvm.headerText = "最近90天"
                                break;
                        }


                    } else {
                        window.failedNotify(Toast, resp.info.msg);
                    }
                });
            },
            // 返回
            back() {
                this.$router.go(-1)
            },
            phoneBack() {
                if (this.mvvm.formDataVisible) {
                    this.mvvm.formDataVisible = false;
                } else {
                    this.$router.go(-1)
                }
                if (window.history && window.history.pushState) {
                    history.pushState(null, null, document.URL);
                    window.addEventListener('popstate', this.phoneBack, false);//false阻止默认事件
                }
            }
        }, created() {

            // 获取所有订单
            this.getAllOrders(-2);
            // 获取所有产品目录
            this.getAllProductCategory();
            jQuery.validator.addMethod("cstdate", function (value, element) {
                var email_number = /^\d{4}-\d{1,2}-\d{1,2}\s\d{2}:\d{2}(:\d{2})?$/
                return this.optional(element) || email_number.test(value);
            }, "<label class='error'>日期格式不正确</label>");
            jQuery.validator.addMethod("products", function (value, element) {
                var email_number = /^([A-Za-z\u4e00-\u9fa5]{1,}(\*\d{1,2})?\+?)+$/
                return this.optional(element) || email_number.test(value);
            }, "<label class='error'>产品格式不正确</label>");


        }, mounted() {
            if (window.history && window.history.pushState) {
                history.pushState(null, null, document.URL);
                window.addEventListener('popstate', this.phoneBack, false);//false阻止默认事件
            }
        },
        destroyed() {
            window.removeEventListener('popstate', this.phoneBack, false);//false阻止默认事件
        }
    }
</script>

<style scoped>
    .order-item {
        background-color: white;
        padding: 2%;
        margin: 5% 2.5%;
        -webkit-border-radius: 5px;

        -moz-border-radius: 5px;

        border-radius: 5px;

        -webkit-box-shadow: #666 0px 0px 10px;

        -moz-box-shadow: #666 0px 0px 10px;

        box-shadow: #666 0px 0px 10px;
    }

    .yd-popup-content {
        background-color: white;
    }
</style>
